/*
 * Copyright (c) 2006-2021, RT-Thread Development Team
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author       Notes
 * 2021-10-24     hehung       the first version - pyroelectric infrared sensor
 *                             热释电红外传感器模块   --   not used
 */

#include "app_pir.h"
#include "board.h"

#define PIR_DIGITAL_EN       0u
#define PIR_ANALOG_EN        1u
#define PIR_METHOD_EN        PIR_DIGITAL_EN


#if (PIR_METHOD_EN == PIR_ANALOG_EN)
#define ADC_DEV_NAME         "adc0"    /* ADC 设备名称 */
#define ADC_DEV_CHANNEL       4      /* ADC 通道  PB2 */
#define REFER_VOLTAGE         330      /* 参考电压 3.3V,数据精度乘以 100 保留 2 位小数*/
#define CONVERT_BITS          (1 << 10) /* 转换位数为 10 位 */

rt_adc_device_t adc_dev;
#elif(PIR_METHOD_EN == PIR_DIGITAL_EN)
uint8_t pir_detect_pin = 0u;
#endif

void PIR_AppInit(void)
{
#if (PIR_METHOD_EN == PIR_ANALOG_EN)
    rt_err_t ret = RT_EOK;

    /* 查找设备 */
    adc_dev = (rt_adc_device_t)rt_device_find(ADC_DEV_NAME);
    if (adc_dev == RT_NULL)
    {
        rt_kprintf("adc sample run failed! can't find %s device!\n", ADC_DEV_NAME);
    }

    /* 使能设备 */
    ret = rt_adc_enable(adc_dev, ADC_DEV_CHANNEL);
    if(ret != 0)
    {
        rt_kprintf("adc sample enabled failed!");
    }
#elif(PIR_METHOD_EN == PIR_DIGITAL_EN)
    pir_detect_pin = rt_pin_get("PB.2");
    rt_pin_mode(pir_detect_pin, PIN_MODE_INPUT);
#endif
}

static void PIR_ManageEntry(void *parameter)
{
#if (PIR_METHOD_EN == PIR_ANALOG_EN)
    rt_uint32_t value, vol;
    rt_err_t ret = RT_EOK;
#endif
    PIR_AppInit();

    while(1)
    {
#if (PIR_METHOD_EN == PIR_ANALOG_EN)
        /* 读取采样值 */
        value = rt_adc_read(adc_dev, ADC_DEV_CHANNEL);
//        rt_kprintf("the value is :%d \n", value);

        /* 转换为对应电压值 */
        vol = value * REFER_VOLTAGE / CONVERT_BITS;
        rt_kprintf("the voltage is :%d.%02d \n", vol / 100, vol % 100);
#elif(PIR_METHOD_EN == PIR_DIGITAL_EN)
        rt_kprintf("Is checked body? :%d \n", rt_pin_read(pir_detect_pin));
#endif
        rt_thread_mdelay(1000);
    }

    /* 关闭通道 */
//    ret = rt_adc_disable(adc_dev, ADC_DEV_CHANNEL);
}

static void PIR_SelfTest(void)
{
    rt_thread_t pir_thread;

    pir_thread = rt_thread_create("RTC Thread Manage",     /*线程名字*/
                                   PIR_ManageEntry,/*线程入口函数*/
                                   RT_NULL, /*线程入口函数参数*/
                                   1024,    /*线程栈大小*/
                                   6,       /*线程优先级*/
                                   10);     /*线程时间片*/

    if(pir_thread != RT_NULL)
    {
        rt_kprintf("PIR Thread Created Success!\n");
        rt_thread_startup (pir_thread);
    }
    else
    {
        rt_kprintf("PIR Thread Create Failed!\n");
    }
}

#ifdef FINSH_USING_MSH
MSH_CMD_EXPORT(PIR_SelfTest, Test pyroelectric infrared sensor);
#endif
